import time
import uuid
from pathlib import Path
from typing import Optional
import logging

logger = logging.getLogger(__name__)

def generate_file_key(task_id: str, filename: str = "output.jpg") -> str:
    """
    生成COS文件键
    
    Args:
        task_id: 任务ID
        filename: 文件名（用于提取扩展名）
        
    Returns:
        str: COS文件键，格式: facefusion/{task_id}_{random}.jpg
    """
    file_ext = Path(filename).suffix.lower() or '.jpg'
    random_suffix = uuid.uuid4().hex[:8]
    return f"facefusion/{task_id}_{random_suffix}{file_ext}"

def upload_to_cos(
    cos_client,
    cos_config_info: dict,
    local_path: str,
    file_key: str
) -> Optional[str]:
    """
    上传文件到COS桶（通过内网）
    
    Args:
        cos_client: COS客户端实例
        cos_config_info: COS配置信息
        local_path: 本地文件路径
        file_key: COS文件键
        
    Returns:
        Optional[str]: CDN URL if success, None if failed
    """
    try:
        file_size = Path(local_path).stat().st_size / (1024 * 1024)  # MB
        logger.info(f"开始上传到COS: {file_key} ({file_size:.1f}MB)")
        
        # 通过内网上传到COS（免流量费）
        response = cos_client.put_object_from_local_file(
            Bucket=cos_config_info['bucket'],
            LocalFilePath=local_path,
            Key=file_key,
            ACL='public-read',  # 设置为公共读，允许CDN访问
            Metadata={
                'upload-time': str(int(time.time())),
                'source': 'facefusion-api',
                'processed': 'true',
                'region': cos_config_info['region'],
                'mode': 'extreme_beauty'
            }
        )
        
        # 生成CDN链接（用户通过CDN加载图片）
        cdn_url = f"https://{cos_config_info['cdn_domain']}/{file_key}"
        logger.info(f"COS上传成功: {cdn_url}")
        
        return cdn_url
        
    except Exception as e:
        logger.error(f"COS上传失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return None
